//
// PcwTextView.cs
//
// Author: 
//  Fredy Ramirez <framirez@pacificcoolwave.com>
//
// Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)
//
//  Creation date: Aug 31, 2011
//  Last modification: 

/*
The MIT License

Copyright (C) 2011 Fredy Ramirez (http://www.pacificcoolwave.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

using System;
using System.IO;
using Gtk;
using Mono.Addins;

namespace Pcw.PcwTextEditor.PcwDocument
{
	/// <summary>
	/// A specialized DocumentView class.
	/// </summary>	
	/// <remarks>
	/// <p>This class is used to represent a main view in a document, showing only text.</p>
	/// <p>It raises relevant events to the document object which raises other events to all add-ins.
	/// That is, when a PcwTextView object raises a DocumentViewChange event Document object raises 
	/// a DocumentViewChange event and so on.</p>
	/// </remarks>
	public class PcwTextView : DocumentView
	{
		private TextBuffer buffer;
		private TextView text_view;
		
		// UndoRedo
		private MementoCaretaker caretaker = new MementoCaretaker();
		private string text_mirror = "";		
		private bool is_undo = false;
		private bool is_redo = false;
		public event EventHandler EnableDisableUndoRedoFeature;
		
		public event DocumentViewEventHandler DocumentViewChange;
		public event DocumentViewEventHandler DocumentViewSelect;
		
		private TextChangedInfo changed_info;
		
		private Statusbar status;
		
		/// <summary>
		/// The TextBuffer object.
		/// </summary>
		public TextBuffer Buffer
		{
			get {return buffer;}
		}
		
		public bool CanUndo {
			get {
				return caretaker.IsUndoPossible();
			}
		}
		
		public bool CanRedo {
			get {
				return caretaker.IsRedoPossible();
			}
		}
		
		public TextChangedInfo ChangedInfo {
			get{
				return changed_info;
			}
		}
		
		/// <summary>
		/// Constructor. Derived from <see cref="DocumentView"/> class.
		/// </summary>
		public PcwTextView (string viewName, string viewLabel, TextView textView, Document viewDocument) : 
			base(viewName, viewLabel, textView, viewDocument)
		{			
			TextTagTable table = new TextTagTable();
			buffer = new TextBuffer(table);
			buffer.Text = "";
			//buffer.Changed += onDocumentViewChanged;
			buffer.DeleteRange += onDeleteRange;
			buffer.InsertText += onInsertText;
			
			changed_info = new TextChangedInfo();
			
			text_view = textView;
			text_view.Buffer = buffer;
			text_view.FocusInEvent += onDocumentViewSelect;
			
			status = new Statusbar();
			status.HasResizeGrip = true;
			
			BoxBotton.PackStart(status, true, true, 0);
			
		}
	
		/// <summary>
		/// Sets the <see cref="TextView"/> font.
		/// </summary>
		/// <param name="fontFamily">
		///   The <see cref="string"/> font family.
		/// </param>
		/// <param name="fontSize">
		///   The <see cref="double"/> font size.
		/// </param>
		public void SetFont(string fontFamily, double fontSize)
		{
			Pango.FontDescription fc = new Pango.FontDescription();
			fc.Family = fontFamily;
			fc.AbsoluteSize = Convert.ToDouble(fontSize * Pango.Scale.PangoScale);
			text_view.ModifyFont (fc);	
		}
	
		/// <summary>
		/// Sets the focus on the <see cref="TextView"/> object.
		/// </summary>		
		public new void GrabFocus()
		{
			text_view.GrabFocus();
		}		

		public void SetStatos (string text)
		{
			status.Pop(1);
			status.Push(1, text);
		}
		
		public void Undo()
		{
			Undo(1);
		}		
		
		public void Undo(int level)
		{
			is_undo = true;
			
            MementoString memento = null;
            for (int i = 1; i <= level; i++)
                memento = caretaker.getUndoMemento();

            if (memento != null)
                SetMemento(memento);

            if (EnableDisableUndoRedoFeature != null)
                EnableDisableUndoRedoFeature(null, null);
			
			is_undo = false;
		}

		public void Redo()
		{
			Redo(1);
		}
		
		public void Redo(int level)
		{
			is_redo = true;
			
            MementoString memento = null;
            for (int i = 1; i <= level; i++)
                memento = caretaker.getRedoMemento();
			
            if (memento != null)
                SetMemento(memento);

            if (EnableDisableUndoRedoFeature != null)
                EnableDisableUndoRedoFeature(null, null);

			is_redo = false;
		}
		
		public void ClearUndoRedo()
		{
			caretaker.Clear();
		}
		
		private void SetMemento (MementoString memento)
		{			
			if (is_undo) {
				if (memento.OperationType == TextChangeType.InsertText) 
					DeleteMementoText(memento);		
				else 
					InsertMementoText(memento);
			}			
			else if (is_redo) {
				if (memento.OperationType == TextChangeType.DeleteText)
					DeleteMementoText(memento);
				else 
					InsertMementoText(memento);
			}			
		}
		
		private void FireDocumentViewChanged()
		{
			ViewDocument.DocInfo.Saved = false;
			if (DocumentViewChange != null) 
				DocumentViewChange(this);
		}

		private void onDocumentViewSelect(object o, FocusInEventArgs args)
		{
			status.Push(1, AddinManager.CurrentLocalizer.GetString("Name: {0}", ViewDocument.DocInfo.Name) + 
				AddinManager.CurrentLocalizer.GetString (" - Ext: {0}", ViewDocument.DocInfo.Extension) + 
			            AddinManager.CurrentLocalizer.GetString (" - Path: {0}", ViewDocument.DocInfo.Path));
			if (DocumentViewSelect != null)
				DocumentViewSelect(this);
		}
		
		private void onDeleteRange(object o, DeleteRangeArgs args)
		{
			string textDeleted = text_mirror;
			textDeleted = textDeleted.Substring(args.Start.Offset, text_mirror.Length - buffer.Text.Length);
			GetMemento(TextChangeType.DeleteText, textDeleted, args.Start.Offset);
			
			changed_info.SetInfo(TextChangeType.DeleteText, textDeleted, args.Start);
			
			FireDocumentViewChanged();
		}
		
		private void onInsertText(object o, InsertTextArgs args)
		{
			GetMemento(TextChangeType.InsertText, args.Text, args.Pos.Offset - args.Text.Length);
			
			TextIter start = args.Pos;
			start.BackwardChars(args.Text.Length);
			
			changed_info.SetInfo(TextChangeType.InsertText, args.Text, start);
			
			FireDocumentViewChanged();
		}
		
		private void GetMemento(TextChangeType operationType, string text, int startPos)
		{
			if (!is_undo && !is_redo) {
				
				MementoString memento = new MementoString(operationType, text, startPos);
				
	           	caretaker.InsertMementoForUndoRedo(memento);
				
	           	if(EnableDisableUndoRedoFeature != null)
	               	EnableDisableUndoRedoFeature(null, null);
			}
			
			text_mirror = buffer.Text;
		}
		
		private void DeleteMementoText(MementoString memento)
		{
			TextIter iter1 = buffer.StartIter;
			iter1.ForwardChars(memento.Pos);
			TextIter iter2 = iter1;
			iter2.ForwardChars(memento.Text.Length);
			buffer.Delete (ref iter1, ref iter2);
		}
		
		private void InsertMementoText(MementoString memento)
		{
			TextIter iter1 = buffer.StartIter;
			iter1.ForwardChars(memento.Pos);
			buffer.Insert(ref iter1, memento.Text);
		}
	}
}

